import time
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import Select
import os


class FormOperation:
    def __init__(self):
        self.driver = webdriver.Chrome()
        self.driver.maximize_window()
        url = 'file:///' + os.path.dirname(os.path.abspath(__file__)) + '/html/注册实例.html'
        self.driver.get(url)

        # 找到B表标签
        b = self.driver.find_element(By.NAME, 'myframe2')
        # 切换到B表 frame
        self.driver.switch_to.frame(b)
        time.sleep(2)

    def register(self):
        # 找到账号输入框并输入
        self.driver.find_element(By.ID, 'userB').send_keys('test2266')
        # 找到密码输入框并输入
        self.driver.find_element(By.ID, 'passwordB').send_keys('test32356')
        # 找到电话号码输入框并输入
        self.driver.find_element(By.ID, 'telB').send_keys('15642353254')
        # 找到邮箱输入框并输入
        self.driver.find_element(By.ID, 'emailB').send_keys('15642353254@163.com')

        # 找到注册用户按钮并点击
        time.sleep(2)
        self.driver.find_element(By.XPATH, '//*[@id="zc"]/fieldset/button').click()

    def drop_down_box(self):
        # 找到下拉框并点击
        s1 = self.driver.find_element(By.ID, 'selectB')
        s1.click()
        time.sleep(2)
        # 创建select对象使用
        select = Select(s1)
        # 通过value选择选项,选择索引为2的选项广州
        select.select_by_index(2)

    def popup(self):
        # 找到弹窗
        self.driver.find_element(By.ID, 'alertB').click()
        time.sleep(2)
        # 切换到alert窗口
        alert = self.driver.switch_to.alert
        # 弹窗确认
        alert.accept()

    def back_homepage(self):
        # 退出到主页面
        time.sleep(2)
        self.driver.switch_to.default_content()

        # 执行js语句滚动条滑动到最顶部
        js = 'window.scrollTo(0,0)'
        self.driver.execute_script(js)

    def quit(self):
        time.sleep(3)
        self.driver.quit()


if __name__ == '__main__':
    fo = FormOperation()
    fo.drop_down_box()
    fo.popup()
    fo.register()
    fo.back_homepage()
    fo.quit()
